<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="permissionTree"
      :props="{label:'name'}"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { tranListTotreeList } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionTree: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    // 获取当前角色权限
    async loadRoleDetail() {
      try {
        const res = await getRoleDetail(this.id)
        console.log('getRoleDetail', res)
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)
        // 保存数据
      } catch (err) {
        console.log('getRoleDetail', err)
      }
    },
    // 加载权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.permissionTree = tranListTotreeList(res.data)
        // 保存数据
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    async doSave() {
      try {
        // 获取选中的权限点
        const permIds = this.$refs.treeRef.getCheckedKeys()
        const res = await assignPerm({ id: this.id, permIds: permIds })
        console.log('assignPerm', res)
        this.$message.success(res.message)
        this.$emit('success')
        // 保存数据
      } catch (err) {
        console.log('assignPerm', err)
      }
    },
    hSubmit() {
      // 确定
      this.doSave()
    },
    hClose() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
